package club.dataresources.controller;

import club.dataresources.common.R;
import club.dataresources.entity.Admin;
import club.dataresources.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*** 后台管理员设置
 *
 * @author Galois
 * 2018-01-24 15:17
 **/

@RequestMapping(value = "/admin")
@Controller
public class AdminAdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 后台登录
     *
     * @param username
     * @param password
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
    public @ResponseBody
    R adminLogin(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            HttpServletRequest request,
            HttpServletResponse response) {
        System.out.println("============后台管理====后台登录=============");
        try {
            Admin admin = new Admin();
            admin.setUsername(username);
            admin.setPassword(password);
            Admin adminUser = adminService.adminLogin(admin);
            if(adminUser!=null){
                //登录通过,将admin对象存进session
                System.out.println("=====标记adminLoginFlag 后台登录通过=====");
                request.getSession().setAttribute("adminLoginFlag",adminUser);
                //页面重定向
                response.sendRedirect("listAdmin");
                return R.ok().put("code",200).put("msg","登录成功,页面重定向");
            }else{
                //未找到该用户或密码错误
                return R.error().put("code",500).put("msg","未找到该用户或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().put("code",500).put("msg","后台服务器异常");
        }
    }
}
